package com.xgc.oauth.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.time.Instant;

/**
 * jwt工具类
 *
 * @author xgc
 * @date 2024/01/10
 */
@Slf4j
public class JwtUtil {

    private static final String PUBLIC_KEY_STR = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5lOAvszLfeSBIoQ2G0hEKRMrEZttQVar1nrOA5MvuW7b8KzHW/XjsKMgnlYP1R/vEcHkt5GbHIFMo5+QOIHHr7lJZjG1RPIK/ufFRYFPcZwsQu3dAwjSbitXkkmF+jlrW6eWvpQa3bH/fem2sLS3z4nVy+PBMazZG8GUD6s/5bwIDAQAB";
    private static final String PRIVATE_KEY_STR = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALmU4C+zMt95IEihDYbSEQpEysRm21BVqvWes4Dky+5btvwrMdb9eOwoyCeVg/VH+8RweS3kZscgUyjn5A4gcevuUlmMbVE8gr+58VFgU9xnCxC7d0DCNJuK1eSSYX6OWtbp5a+lBrdsf996bawtLfPidXL48ExrNkbwZQPqz/lvAgMBAAECgYAh0PUA/CBbBFFTqrUySfj87Agevbdc7h9W3nJLHGXkqyWu0ZglWs68CbpfLCl9en5wDyalrCbmRgehPpAZ2uOnELdXSynmx6YUx05f1AEN6QUJX5ks4cFmxu+XKhT9xS98/FW8mTd6L1LVp9u2e4ms6XuU/iZHIhroH1w28DwHUQJBANdhwt0MX9p1hDTCg+JD7+PQFTvPkIPE8Fzs1hzCBuedpM87omvaMB2lWYgyFM/xPhVtv/AsXjOhPicnq68qw60CQQDclGjXkZshYSCmxW/u+R3m2Vmi171i33jshRKKHQFbxLzkBwZtx1DtQDL4a49R6kEHzLHW6yzu8/PFrIKgKfULAkAdAYN2tYXrK8xkNpYAUNnrukhBx9BUjp84RIUJVnALnUVmy0cycy3rsCsAlo4K+xg7Vo50z+TX2y09pLAQZRf5AkEAgJq+rcClE8cPRGykoE36UxeyHTFvp+/nDu9fKctTeW+xObmm0+Z7lnfxv8jmXLoZhDSiE042enMdU8kKt9r+lQJAIM7HvK7B/blT2o07gWyGdVkiQ6wdIM6wlQPLBAEfj7WaG61QutnNA8h9Vpiiy3rSuHvNyold90PH+8Ws32Mp1w==";


    public static String create(Integer userId, long expiresSeconds) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Algorithm algorithm = getAlgorithm();
        return JWT.create()
                .withClaim("userId", userId)
                .withExpiresAt(Instant.now().plusSeconds(expiresSeconds))
                .sign(algorithm);
    }

    public static DecodedJWT parse(String jwtStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
        Algorithm algorithm = getAlgorithm();
        return JWT.require(algorithm).build().verify(jwtStr);
    }

    private static Algorithm getAlgorithm() throws NoSuchAlgorithmException, InvalidKeySpecException {
        RSAPrivateKey privateKey = RsaUtil.getPrivateKey(PRIVATE_KEY_STR);
        RSAPublicKey publicKey = RsaUtil.getPublicKey(PUBLIC_KEY_STR);
        return Algorithm.RSA256(publicKey, privateKey);
    }

}
